package com.weipt.juc.lock;

/**
 * @author peter.wei 2020/09/10 09:25
 * @version 1.0
 * @company 终生学习
 * @description <br>peter.wei 2020/09/10 09:25 生产者消费者=>线程通讯问题
 * synchronized  wait notify 三剑客
 **/
public class HelloSynPC {

    public static void main(String[] args) {
        Data pc = new Data();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    pc.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}


class Data{
    private static int num = 0;
    public synchronized void increment() throws InterruptedException {
        //需要等待的条件
        while (num!=0){
            this.wait();
        }
        //执行逻辑
        num++;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //逻辑执行完毕，通知别人
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        //需要等待的条件
        while (num==0){
            this.wait();
        }
        //执行逻辑
        num--;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知别人
        this.notifyAll();
    }
}